'use client';

import { Button } from '@/components/ui/button';
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useAuth } from '@/context/authContext';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { post } from '@/lib/request';

export default function RegisterPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  const { setUser, user } = useAuth();

  useEffect(() => {
    if (user) {
      router.push('/');
    }
  }, [user, router]);

  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      toast.error('两次密码不一致');
      return;
    }
    setIsLoading(true);
    try {
      const jsonData = { username, password };
      const response = await post('/auth/register', jsonData);
      setUser(response.data);
      toast.success('注册成功，将自动登录');
      router.push('/');
    } catch (error: any) {
      if (error.status == 409) {
        toast.warning('该用户名已经存在，请尝试其他用户名');
      } else {
        toast.error(error.response?.data?.message || error.message);
      }
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex items-center justify-center min-h-screen min-w-[400px] bg-white">
      <Card className="max-w-[350px] w-full mx-4 rounded-2xl border-thin border-gray-200 bg-white shadow-md flex flex-col justify-center">
        <form onSubmit={handleRegister}>
          <CardHeader className="pb-2">
            <CardTitle className="text-3xl font-bold text-center text-wechat mb-2">注册</CardTitle>
            <CardDescription className="text-xs text-center text-gray-400 mb-2">
              请输入用户名和密码
            </CardDescription>
          </CardHeader>
          <CardContent className="grid gap-6 px-6 py-2">
            <div className="grid gap-2">
              <Label htmlFor="username" className="text-sm font-medium text-gray-700">用户名</Label>
              <Input
                id="username"
                type="text"
                placeholder="请输入用户名"
                required
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                disabled={isLoading}
                className="h-12 text-base"
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="password" className="text-sm font-medium text-gray-700">密码</Label>
              <Input
                id="password"
                type="password"
                placeholder="请输入密码"
                required
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                disabled={isLoading}
                className="h-12 text-base"
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="confirmPassword" className="text-sm font-medium text-gray-700">确认密码</Label>
              <Input
                id="confirmPassword"
                type="password"
                placeholder="请再次输入密码"
                required
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                disabled={isLoading}
                className="h-12 text-base"
              />
            </div>
          </CardContent>
          <CardFooter className="flex flex-col gap-2 px-6 pb-6">
            <Button
              type="submit"
              className="w-full text-base font-semibold h-12 rounded-xl"
              disabled={isLoading}
            >
              {isLoading ? '注册中...' : '注册'}
            </Button>
            <p className="mt-2 text-xs text-center text-gray-400">
              已有账号{' '}
              <Link href="/login" className="underline hover:text-wechat transition">立即登入</Link>
            </p>
          </CardFooter>
        </form>
      </Card>
    </div>
  );
}
